﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.Model;
using System.Net;
using StockFinder.Model.Enumerations;
using System.IO;

namespace StockFinder.Services.Extractors.Google
{
    //public class GoogleHistoricPriceExtractor : IHistoricPricesExtractor
    //{
    //    private const string BASE_URL = "http://www.google.com/finance/historical?q={0}:{1}&output=csv";

    //    /* google prefixes symbols with the exchange, which would either be NASDAQ or NYSE
    //     * so try NASDAQ first and then try NYSE */

    //    #region IHistoricPricesExtractor Members

    //    public HistoricPricesExtract GetHistoricPrices(string symbol)
    //    {
    //        HistoricPricesExtract result = null;

    //        #region Try actual symbol first

    //        //create the url - try NASDAQ first
    //        string pricesUrl = string.Format(BASE_URL, "", symbol);

    //        result = GetPricesPageSource(pricesUrl);            

    //        #endregion

    //        #region Stock might have a '.' at the end

    //        //did it work for AMEX?
    //        if (result.HistoricPricesExtractResult == HistoricPricesExtractResult.ERROR)
    //        {
    //            //e.g. STZB -> STZ.B

    //            //no so try NYSE but with a '.' 
    //            pricesUrl = string.Format(BASE_URL, symbol.Exchange, symbol.Name.Insert(symbol.Name.Length - 1, "."));

    //            result = GetPricesPageSource(pricesUrl);
    //        }

    //        #endregion

    //        #region Set SymbolId

    //        //was the result a success?
    //        if (result.HistoricPricesExtractResult == HistoricPricesExtractResult.SUCCESS)
    //        {
    //            //yes so set the symbol reference for the prices
    //            result.DailyPrices.ForEach(price => price.SymbolId = symbol.SymbolId);
    //        }
    //        else
    //        {
    //            //something went wrong
    //        }

    //        #endregion

    //        return result;
    //    }

    //    public HistoricPricesExtract GetHistoricPrices(DateTime fromDate, DateTime toDate, string symbol)
    //    {
    //        throw new NotImplementedException();
    //    }

    //    #endregion

    //    private List<DailyPrice> ExtractDailyPricesFromSource(string pageSource)
    //    {
    //        if (string.IsNullOrEmpty(pageSource))
    //        {
    //            //empty page source
    //            throw new ArgumentNullException("pageSource can not be null or empty in this context");
    //        }

    //        List<DailyPrice> dailyPrices = new List<DailyPrice>();

    //        string[] dailyPriceLines = pageSource.Split(new char[] { '\n' });

    //        //check we have some prices
    //        if (dailyPriceLines.Length > 1)
    //        {
    //            //loop each price line, starting from second line (top line is headers)
    //            for (int dailyPriceLineIndex = 1; dailyPriceLineIndex < dailyPriceLines.Length; dailyPriceLineIndex++)
    //            {
    //                string dailyPriceLine = dailyPriceLines[dailyPriceLineIndex];

    //                //split up line into price components e.g open, close etc
    //                string[] dailyPriceComponents = dailyPriceLine.Split(new char[] { ',' });

    //                //make sure we have all componets
    //                if (dailyPriceComponents.Length == 6)
    //                {
    //                    //create the daily price
    //                    DailyPrice dailyPrice = new DailyPrice()
    //                    {
    //                        PriceDate = Convert.ToDateTime(dailyPriceComponents[0]),
    //                        Open = Convert.ToDecimal(dailyPriceComponents[1]),
    //                        High = Convert.ToDecimal(dailyPriceComponents[2]),
    //                        Low = Convert.ToDecimal(dailyPriceComponents[3]),
    //                        Close = Convert.ToDecimal(dailyPriceComponents[4]),
    //                        Volume = Convert.ToInt64(dailyPriceComponents[5]),
    //                        //AdjustedClose = Convert.ToDecimal(dailyPriceComponents[6])
    //                    };

    //                    //add to list
    //                    dailyPrices.Add(dailyPrice);
    //                }
    //            }
    //        }

    //        return dailyPrices;
    //    }

    //    public HistoricPricesExtract GetPricesPageSource(string url)
    //    {
    //        HistoricPricesExtract result = new HistoricPricesExtract();

    //        //now get the spreadsheet
    //        HttpWebRequest webRequest = HttpWebRequest.Create(url) as HttpWebRequest;

    //        HttpWebResponse webResponse = null;

    //        try
    //        {
    //            webResponse = (HttpWebResponse)webRequest.GetResponse();

    //            //got a response
    //            result.HistoricPricesExtractResult = HistoricPricesExtractResult.SUCCESS;
    //        }
    //        catch (WebException webException)
    //        {
    //            //timeout?
    //            //if (webException.Status == WebExceptionStatus.Timeout)
    //            //{
    //            //    //probably internet down so quit
    //            //    extraction.HistoricPricesExtractResult = HistoricPricesExtractResult.TIMEOUT;
    //            //}

    //            result.Message = webException.Status.ToString();
    //            result.HistoricPricesExtractResult = HistoricPricesExtractResult.ERROR;
    //        }

    //        //was the page hit a success?
    //        if (result.HistoricPricesExtractResult == HistoricPricesExtractResult.SUCCESS)
    //        {
    //            string pageSource = null;

    //            using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
    //            {
    //                pageSource = streamReader.ReadToEnd();
    //            }

    //            /* check that prices exist for this symbol */

    //            if (pageSource.IndexOf("not found") > -1)
    //            {
    //                //doesnt exist so quit
    //                result.HistoricPricesExtractResult = HistoricPricesExtractResult.PRICES_NOT_EXIST;
    //            }
    //            else
    //            {
    //                //does so extract prices
    //                result.DailyPrices = ExtractDailyPricesFromSource(pageSource);                    
    //            }
    //        }

    //        return result;
    //    }

    //    public bool LoadHistoricPrices(DateTime fromDate, DateTime toDate, string symbol)
    //    {
    //        throw new NotImplementedException();
    //    }

    //    public bool LoadHistoricPrices(DateTime fromDate, DateTime toDate, string symbolName, List<DailyPrice> dailyPricesTransporter)
    //    {
    //        throw new NotImplementedException();
    //    }
    //}
}
